import React from 'react'

const Component = () => {
  //获取房间的ID
  let [searchParams] = React.Router.useSearchParams()
  let [rid, SetID] = React.useState(searchParams.get('rid') ? searchParams.get('rid') : 0)
  let [guest, SetGuest] = React.useState([])
  let [coupon, SetCoupon] = React.useState([])
  let [DateShow, SetDateShow] = React.useState(false)
  let [GuestShow, SetGuestShow] = React.useState(false)
  let [CouponShow, SetCouponShow] = React.useState(false)
  let [PayShow, SetPayShow] = React.useState(false)
  let [price, SetPrice] = React.useState(0)
  let [OriginPrice, SetOriginPrice] = React.useState(0)
  let [day, SetDay] = React.useState(0)

  // 房间信息
  let [room, SetRoom] = React.useState({
    name: '',
    price: '0',
    state: '',
    thumb_text: '',
    flag_text: [],
    content: '',
    total: 0,
  })

  //订单信息
  let [order, SetOrder] = React.useState({
    roomid: rid,
    busid: React.Business.id,
    remark: '',
    //价格信息
    origin_price: room.price,
    price: '',
    //优惠券
    couponid: '',
    couponstr: '',
    //日期
    datestr: '',
    starttime: 0,
    endtime: 0,
    //住客
    guest: '',
    gueststr: '',
    guestids: [],
    //支付方式
    paystr: '余额支付',
    pay: 'money'
  })

  //支付信息
  let [paylist, SetPay] = React.useState([[
    { label: '余额支付', value: 'money' },
    { label: '微信支付', value: 'wx' },
    { label: '支付宝支付', value: 'zfb' },
  ]])

  // 钩子函数
  React.useEffect(() => {
    RoomData()
    GuestData()
    CouponData()
  }, [])

  //当订单信息有变化，就重新计算价格
  React.useEffect(() => {
    Total()
  }, [order])

  // 房间信息
  const RoomData = async () => {
    var result = await React.HTTP.post('/room/info', { rid })

    if (result.code == 0) {
      React.error(result.msg, () => { })
      return false
    }

    SetRoom(result.data)
  }

  // 住客信息
  const GuestData = async () => {
    var result = await React.HTTP.post('/room/guest', { busid: React.Business.id })

    if (result.code == 0) {
      React.error(result.msg, () => { });
      return false;
    } else {
      SetGuest(result.data)
    }
  }

  // 优惠卷数据方法
  const CouponData = async () => {
    var result = await React.HTTP.post('/room/coupon', { busid: React.Business.id })

    if (result.code == 1) {
      var list: any = []

      result.data.map((item: any) => {
        list.push({
          label: `${item.coupon.title}-${item.coupon.rate * 10}折`,
          value: item.id,
          rate: item.coupon.rate
        })
      })

      //给二维数组结构
      list = [list]
      SetCoupon(list)
    }
  }

  // 日期选择的方法
  const DateConfirm = async (val: any) => {
    SetDateShow(false)

    // var datestr = `2024-03-20 - 2024-03-25`
    var datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`

    //获取到开始时间和结束时间
    //标准时间转换为时间戳
    var starttime = Date.parse(new Date(val[0]).toLocaleDateString()) / 1000
    var endtime = Date.parse(new Date(val[1]).toLocaleDateString()) / 1000

    SetOrder({
      ...order,
      starttime,
      endtime,
      datestr
    })
  }

  //住客选择方法
  const GuestChange = async (value: string[]) => {
    var gueststr: any = []
    var guestids: any = []

    //循环遍历
    guest.map((item: any) => {
      if (value.includes(item.id)) {
        gueststr.push(item.nickname)
        guestids.push(item.id)
      }
    })

    var str = gueststr.join('、')
    var ids = guestids.join(',')

    //设置订单数据
    SetOrder({
      ...order,
      gueststr: str,
      guest: ids,
      guestids
    })
  }

  //优惠券确认
  const CouponChange = async (value: any) => {
    SetCouponShow(false)

    var couponstr = ''

    //获取picker第一项
    var list: any = coupon[0]

    list.map((item: any) => {
      if (item.value == value[0]) {
        couponstr = item.label
      }
    })

    SetOrder({
      ...order,
      couponstr,
      couponid: value[0],
    })
  }

  //计算价格
  const Total = () => {
    var starttime = order.starttime
    var endtime = order.endtime

    //时间差
    var day: any = endtime - starttime
    day = day / 86400
    day = day.toFixed(0)
    day = parseInt(day)

    //原价 时间差*房间原价
    var origin_price = day * parseFloat(room.price)
    var price = origin_price

    //是否有选择优惠券
    if (order.couponid) {
      var rate = 1
      var list: any = coupon[0]
      //找寻当前所选择的优惠券信息
      list.map((item: any) => {
        if (item.value == order.couponid) {
          rate = item.rate
        }
      })

      //计算折扣后的价格
      price = origin_price * rate
    }

    //修改价格
    SetPrice(price)
    SetOriginPrice(origin_price)
    SetDay(day)
  }

  //订单备注
  const RemarkChange = (e: any) => {
    SetOrder({
      ...order,
      remark: e
    })
  }

  // 支付方式
  const PayChange = async (value: any) => {
    SetPayShow(false)

    var paystr = ''

    //获取picker第一项
    var list: any = paylist[0]

    list.map((item: any) => {
      if (item.value == value[0]) {
        paystr = item.label
      }
    })

    SetOrder({
      ...order,
      paystr,
      pay: value[0],
    })
  }

  //提交订单
  const confirm = async () => {
    var result = await React.UI.Dialog.confirm({
      content: '是否确认提交订单'
    })

    if (!result) {
      return false
    }


    //组装数据
    var data = {
      busid: order.busid,
      roomid: order.roomid,
      guest: order.guest,
      starttime: order.starttime,
      endtime: order.endtime,
      couponid: order.couponid ? order.couponid : 0,
      remark: order.remark,
      pay: order.pay ? order.pay : 'money'
    }

    if (!data.starttime || !data.endtime) {
      React.error('请选择入住时间', () => { })
      return false
    }

    if (!data.guest) {
      React.error('请选择住客信息', () => { })
      return false
    }

    var result = await React.HTTP.post('/room/add', data)

    if (result.code == 0) {
      React.error(result.msg, () => { })
      return false
    } else {
      //跳转到订单详情界面
      React.success(result.msg, () => {
        React.navigate(result.url)
      })
    }
  }

  return (
    <>
      <link rel='stylesheet' href='/assets/css/confirm.css' />

      <div className='skeleton'>
        <div className="detail">
          <div className="thumb">
            <img src={room.thumb_text} alt="" />
          </div>
          <div className="right">
            <p>{room.name}</p>
            <p>￥{room.price} / 晚</p>
            <div className="tips">
              {room.flag_text && room.flag_text.map((flag: any, index: any) => <span key={index}> {flag} </span>)}
            </div>
          </div>
        </div>

        <div className='skeleton_rect'>
          {/* 入住日期 */}
          <div className="item">
            <label>入住日期</label>
            <React.UI.Input type="text" className="item_right" placeholder="请选择入住日期" value={order.datestr} onClick={() => SetDateShow(true)} />

            {/* 日期选择 */}
            <React.UI.CalendarPicker
              visible={DateShow}
              min={new Date()}
              selectionMode='range'
              onClose={() => SetDateShow(false)}
              onMaskClick={() => SetDateShow(false)}
              onConfirm={DateConfirm}
            >
            </React.UI.CalendarPicker>
          </div>

          {/* 住客信息 */}
          <div className="item">
            <label>住客信息</label>
            <React.UI.Input type="text" className="item_right" placeholder="请选择住客信息" value={order.gueststr} onClick={() => SetGuestShow(true)} />
            <button type="button" className="btn">
              <React.Router.Link to={'/guest/add'}>添加</React.Router.Link>
            </button>

            {/* 弹出层组件 */}
            <React.UI.Popup
              visible={GuestShow}
              onMaskClick={() => SetGuestShow(false)}
              destroyOnClose
            >
              <div
                style={{ height: '40vh', overflowY: 'scroll', padding: '20px' }}
              >
                <React.UI.CheckList
                  multiple={true}
                  defaultValue={order.guestids}
                  onChange={GuestChange}
                >
                  {guest && guest.map((item: any, key: number) =>
                    <React.UI.CheckList.Item key={key} value={item.id}>
                      {item.nickname}
                    </React.UI.CheckList.Item>
                  )}
                </React.UI.CheckList>

                <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestShow(false)}>确认</React.UI.Button>

              </div>
            </React.UI.Popup>
          </div>
        </div>

        {/* 优惠券 */}
        {coupon[0] &&
          <div className='skeleton_price'>
            <div className='tips'>优惠券</div>
            <p>{order.couponstr}</p>
            <React.UI.Button size="mini" color="primary" onClick={() => SetCouponShow(true)}>选择</React.UI.Button>

            {/* 弹框选项 */}
            <React.UI.Picker
              columns={coupon}
              visible={CouponShow}
              onClose={() => SetCouponShow(false)}
              onConfirm={CouponChange}
            >
            </React.UI.Picker>
          </div>
        }

        {/* 支付方式 */}
        <div className='skeleton_price'>
          <div className="tips">支付方式</div>
          <p>{order.paystr}</p>
          <React.UI.Button size="mini" color="primary" onClick={() => SetPayShow(true)}>选择</React.UI.Button>

          <React.UI.Picker
            columns={paylist}
            visible={PayShow}
            onClose={() => SetPayShow(false)}
            onConfirm={PayChange}
          >
          </React.UI.Picker>
        </div>

        {/* 订单备注 */}
        <div className='skeleton_price'>
          <div className="tips">订单备注</div>
          <React.UI.Input placeholder="请输入订单备注" value={order.remark} onChange={RemarkChange} clearable />
        </div>

        {/* 房间费用 */}
        <div className="skeleton_price">
          <div className="tips">房间费用</div>
          <div className="prices">
            <span>￥{OriginPrice}</span>
            <span>共 {day} 晚</span>
          </div>
        </div>
      </div>

      {/* 支付 */}
      <div className="comfirm_foot-bar">
        {price == OriginPrice ?
          <div className="text">
            <span>总价:</span>
            <span>￥{price}</span>
          </div> :
          <div className="text">
            <span>优惠价格:</span>
            <span>￥{price}</span>
            <s>原价：￥{OriginPrice}</s>
          </div>
        }

        <React.UI.Button onClick={confirm} color='primary' disabled={room.state ? false : true}>提交订单</React.UI.Button>
      </div>

    </>
  )
}

export default Component
